package queue_stack.queue.impl;

import queue_stack.queue.Queue;

import java.util.NoSuchElementException;

public class MyLinkedQueue<E> implements Queue<E> {
    private class Node {
        private E value;
        private Node next;

        public Node(E value) {
            this.value = value;
        }
    }
    // 头节点
    private Node head;
    // 尾节点
    private Node tail;
    private int size;

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new NoSuchElementException("队列为空!");
        }
        Node first = head;
        head = head.next;
        if (head == null) {
            tail = null;
        }
        first.next = null;
        size --;
        return first.value;
    }

    @Override
    public E getFont() {
        return head.value;
    }

    @Override
    public void enqueue(E e) {
        Node node = new Node(e);
        Node last = tail;
        tail = node;
        // 队列为空
        if (last == null) {
            head = node;
        }else {
            last.next = node;
        }
        size ++;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node node = head;
        sb.append("front [");
        while (node != null) {
            sb.append(node.value);
            if (node.next != null) {
                sb.append(",");
            }
            node = node.next;
        }
        sb.append("] tail");
        return sb.toString();
    }
}
